package smartcrud.spring.controllers.account;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import smartcrud.spring.models.rbac.User;
import smartcrud.spring.models.rbac.UserService;

@Controller
public class LoginController {
	private static final Log logger = LogFactory.getLog(LoginController.class);
	
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginForm() {
		return "adminLogin";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(
			HttpServletRequest req,
			HttpSession session,
			@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "password", required = false) String password) {
		if (username == null || password == null) {
			return "adminLogin";
		} else {
			User user = userService.connect(username, password);
			if (user == null) {
				return "adminLogin";
			} else {
				session.setAttribute("user", user.getUsername());
				session.setAttribute("userid", user.getId());
				session.setAttribute("menuAsString",
						userService.getMenuAsString(req, user.getId()));
				// 这里不加redirect那么地址栏会保留原有地址back.admin/login，而这个地址是被排除在sitemesh
				// filter之外的
				// 导致welcome页面没有被decorate，因此必须使用redirect改变address bar地址.
				// 而redirect后面只能接RequestMapping吗？
				// 如果我写redirect:back/admin/welcome会报这样的错误：
				// No mapping found for HTTP request with URI
				// [/spring/back/admin/welcome] in DispatcherServlet with name
				// 'spring'
				return "redirect:/welcome";
			}
		}
	}

	@RequestMapping("/welcome")
	public String welcome() {
		return "admin/welcome";
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/login";
	}
}
